<template>
  <div class="app-container">

    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="syncTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:vote:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:vote:remind']"
          type="warning"
          plain
          icon="el-icon-bell"
          size="mini"
          @click="handleRemind"
        >提醒</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:vote:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['community:vote:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="voteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="投票ID" align="center" prop="voteId" width="90" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status==='正在进行'?'success':'info'">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="creater" width="90" />
      <el-table-column label="创建时间" align="center" prop="syncTime" width="170" />
      <el-table-column label="截止时间" align="center" prop="endTime" width="170" />
      <!--      <el-table-column label="参与人数" align="center" prop="voteNumber" width="80"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['community:vote:query']"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >统计</el-button>
          <el-button
            v-hasPermi="['community:vote:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['community:vote:remind']"
            size="mini"
            type="text"
            icon="el-icon-bell"
            @click="handleRemind(scope.row)"
          >提醒</el-button>
          <el-button
            v-hasPermi="['community:vote:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加业委会投票对话框 -->
    <el-dialog :title="title" :visible.sync="openAdd" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10 }"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="投票问题" prop="question">
          <el-input v-model="form.question" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            style="margin-right: 5px"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            style="width: 100px"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新选项</el-button>
        </el-form-item>
        <el-form-item label="投票群组" prop="groups">
          <el-select v-model="selectedGroup" multiple size="small" placeholder="请选择">
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            clearable
            size="small"
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="选择截止时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改业委会投票对话框 -->
    <el-dialog :title="title" :visible.sync="openEdit" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10 }"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="投票问题" prop="question">
          <el-input v-model="form.question" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            style="margin-right: 5px"
            :disable-transitions="false"
          >
            {{ tag }}
          </el-tag>
        </el-form-item>
        <el-form-item label="投票群组" prop="groups">
          <el-select v-model="selectedGroup" disabled multiple size="small" placeholder="请选择">
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            size="small"
            @blur="dateChangeFormat"
            clearable
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="选择截止时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listVote, getVote, delVote, addVote, updateVote } from '@/api/owner/vote'
import { listGroup } from '@/api/owner/group'
import { dateFormat } from '@/utils/dateUtils'

export default {
  name: 'Vote',
  components: {
  },
  data() {
    var validateOptions = (rule, value, callback) => {
      if (this.dynamicTags.length < 2) {
        callback(new Error('请输入至少两个投票选项'))
      } else {
        callback()
      }
    }
    var validateGroups = (rule, value, callback) => {
      if (this.selectedGroup.length === 0) {
        callback(new Error('请选择至少一个群组进行投票'))
      } else {
        callback()
      }
    }
    return {
      // 新增或修改表单校验规则
      rules: {
        title: [
          { required: true, message: '请输入投票标题', trigger: 'blur' },
          // { validator: validatePass, trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
        ],
        question: [
          { required: true, message: '请明确输入待投票问题!', trigger: 'blur' },
        ],
        options: [
          { validator: validateOptions, trigger: 'change' }
        ],
        groups: [
          { validator: validateGroups, trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请选择投票截止日期', trigger: 'blur' }
        ]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业委会投票表格数据
      voteList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      openAdd: false,
      openEdit: false,
      // 新增或修改投票的表单参数
      form: {},
      // 投票查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        question: null,
        options: null,
        groups: null,
        creater: null,
        syncTime: null,
        endTime: null,
        viewNumber: null,
        voteNumber: null,
        communityId: null
      },
      // 投票搜索中的日期区间
      dateRange: [],
      // 投票选项标签
      dynamicTags: [],
      // 标签输入框可见
      inputVisible: false,
      // 标签输入框输入值
      inputValue: '',
      // 群组选项
      groupList: [],
      // 已选择的群组
      selectedGroup: [],
      // 规则控制:投票截止时间不能早于当前
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
    }
  },
  created() {
    this.getList()
    this.getGroupList()
  },
  methods: {

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 查询业委会投票列表 */
    getList() {
      this.loading = true
      listVote(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        // 给后端返回的投票列表逐项添加状态字段（正在进行、已截止）
        const tmpList = response.rows.reverse()
        const now = new Date()
        for (let i = 0; i < tmpList.length; i++) {
          const end = new Date(tmpList[i].endTime)
          if (end > now) {
            tmpList[i].status = '正在进行'
          } else {
            tmpList[i].status = '已截止'
          }
        }
        this.voteList = tmpList
        this.total = response.total
        this.loading = false
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const voteIds = row.voteId || this.ids
      this.$confirm('是否确认删除投票编号为"' + voteIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delVote(voteIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },

    /** 查看投票统计情况 */
    handleView(row) {
      this.$router.push('/owner/voteInfo/' + row.voteId)
      // this.$router.push("/owner/member/" + row.groupId);
    },

    /** 提醒按钮操作 */
    handleRemind(row) {
      const voteIds = row.voteId || this.ids
      this.$confirm('是否确认向投票编号"' + voteIds + '"的目标人群发送提醒投票通知?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        // return delVote(voteIds);
      }).then(() => {
        this.getList()
        this.msgSuccess('通知发送成功')
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.setDynamicTags()
      this.setGroupOptions()
      this.openAdd = true
      this.title = '添加业委会投票'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const voteId = row.voteId || this.ids
      getVote(voteId).then(response => {
        this.form = response.data
        this.setDynamicTags()
        this.setGroupOptions()
        // 准备好数据后打开对话框
        this.openEdit = true
        this.title = '修改业委会投票'
      })
    },
    dateChangeFormat() {
      this.form.endTime = dateFormat('YYYY-mm-dd HH:MM:SS', this.form.endTime)
    },
    /** 提交按钮 */
    submitForm() {
      // this.form.groups = this.form.groups.toString()
      this.form.groups = this.selectedGroup.join(',')
      this.form.options = this.dynamicTags.join(',')
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.voteId != null) {
            // console.log('11111111111', this.form.endTime)
            // this.form.endTime = dateFormat('YYYY-mm-dd HH:MM:SS', this.form.endTime)
            updateVote(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.openEdit = false
              this.getList()
            })
          } else {
            const createTime = new Date()
            this.form.syncTime = dateFormat('YYYY-mm-dd HH:MM:SS', createTime)
            this.form.endTime = dateFormat('YYYY-mm-dd HH:MM:SS', this.form.endTime)
            this.form.viewNumber = 0
            this.form.voteNumber = 0
            // console.log(this.form)
            addVote(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.openAdd = false
              this.getList()
            })
          }
        }
      })
    },

    // 取消按钮
    cancel() {
      this.openAdd = false
      this.openEdit = false
      this.reset()
    },

    // 投票群组从form.groups分割得到
    setGroupOptions() {
      if (this.form.groups === null || this.form.groups.length === 0) {
        this.selectedGroup = []
      } else {
        this.selectedGroup = this.form.groups.split(',')
      }
    },

    // 查询可选择的群组列表
    getGroupList() {
      const groupQueryParams = {
        pageNum: 1,
        pageSize: 50,
        groupName: null,
        communityId: null
      }
      listGroup(groupQueryParams).then(response => {
        const data = response.rows
        const tmpList = []
        data.forEach((item,index,array) => {
          tmpList.push({
            value: item.groupId,
            label: item.groupName
          })
        })
        this.groupList = tmpList
      })
    },

    // 选项从form.options分割得到
    setDynamicTags() {
      if (this.form.options.length === 0) {
        this.dynamicTags = []
      } else {
        this.dynamicTags = this.form.options.split(',')
      }
    },

    // 投票选项的动态标签控制
    // 删除标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    // 新标签输入、验证合法、写入选项数组
    // handleInputConfirm() {
    //   let inputValue = this.inputValue;
    //   if (inputValue) {
    //     this.dynamicTags.push(inputValue);
    //   }
    //   this.inputVisible = false;
    //   this.inputValue = '';
    // },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue === '') {
        this.inputVisible = false
        this.inputValue = ''
      } else if (this.dynamicTags.includes(inputValue)) {
        this.$message.error('投票选项禁止重复哦！')
      } else {
        this.dynamicTags.push(inputValue)
        this.inputVisible = false
        this.inputValue = ''
      }
    },
    // 点击"+ 新选项"按钮 显示新选项标签输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 新增或修改投票的表单重置
    reset() {
      this.form = {
        voteId: null,
        title: null,
        content: null,
        question: null,
        options: '同意,不同意,弃权',
        groups: null,
        creater: null,
        syncTime: null,
        endTime: null,
        viewNumber: null,
        voteNumber: null,
        communityId: null
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.voteId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

  }
}
</script>

<style>
.context p {
  text-indent: 2em;
  display: block;
  /* margin-block-start: 1em; */
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  margin: 0 0;
  padding: 0 0;
}
</style>
